package com.crscd.springbootmapper4.dao;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-05-31 下午2:45
 */
@Slf4j
public class ListStringTypeHandler implements TypeHandler<List<String>> {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(i, mapper.writeValueAsString(strings));
        } catch (JsonProcessingException e) {
            log.warn("convert type error", e);
        }
    }

    @Override
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        return convertToStringList(resultSet.getString(s));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        return convertToStringList(resultSet.getString(i));
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        return convertToStringList(callableStatement.getString(i));
    }

    private List<String> convertToStringList(String json) {
        if (null == json || json.isEmpty()) {
            return new ArrayList<>();
        }
        JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, String.class);
        try {
            return mapper.readValue(json, javaType);
        } catch (IOException e) {
            log.warn("convert type error", e);
        }
        return new ArrayList<>();
    }
}
